import React, {Component} from 'react';
import {Relax} from 'iflux2';
import {Map} from 'immutable';
import moment from 'moment';
import {Table, Popconfirm, Button, Row, Col, Icon, message} from 'antd';
import { Link } from 'react-router'
import {orderListQL} from '../ql';
import {columns} from '../constant/columns';
import OrderTable from 'components/OrderTable';
import Image from 'components/Image'
import ReceiptButton from '../../receipt-common/receipt-button';
import noop from 'util/noop';


@Relax
export default class OrderList extends Component {
    static defaultProps = {
        orderList: orderListQL,
        pagination: Map(),

        queryOrderList: noop,
        receipt: noop,
        changePageCode: noop,
        resetPagination: noop,
        completeOrder: noop,
    }


    constructor(props) {
        super(props);

        this.pageWrapper = null;
        this.title = ["确定收款吗？", "订单收款中，请稍等..."];
        this.okText = ["确定", <Icon type="loading"><span className="ml5">确定</span></Icon>];

        this.state = {
            receipt_loading: false,
            tid: '',
            loading: true,

        }
    }

    componentDidMount() {
        this.props.queryOrderList().then(()=>{
            this.setState({loading: false});
        }).catch(()=>{
            console.log('err');
            this.setState({loading: false});
        });

        if(window.document.getElementById("react-content")){
            this.pageWrapper = window.document.getElementById("react-content").getElementsByClassName("page-wrapper")[0];
        }
    }


    render() {
        const {orderList, pagination} = this.props;
        const {loading} = this.state;

        const orderHeader = (
            <Table dataSource={[]}
                   columns={this.renderHeaderColumns()}
                   pagination={false}/>
        );

        const page = {
            current: pagination.get('pageNum'),
            total: pagination.get('totalCount'),
            pageSize: pagination.get('pageSize'),
            onChange: this.changePageNum,
            onShowSizeChange: this.changePageSize,
            showTotal: (total)=>`共${total}条`,
            showQuickJumper: true,
            showSizeChanger: true,
        }

        return (
            <div>
                <OrderTable loading={loading}
                            tip="loading..."
                            header={orderHeader}
                            rowHeader={this.renderRowHeader}
                            dataSource={orderList.toJS()}
                            columns={this.renderSubColumns()}
                            pagination={page}/>
            </div>
        )
    }


    renderHeaderColumns() {
        return columns.concat([
            {
                title: "操作",
                width: 350,
                key: 'state',
                className:"ant-table-th-right pr8 va-t",
            }
        ]);
    }


    renderRowHeader(record) {
        return (
            <Row>
                <Col span={18}>
                    <div className="buyer-avatar">
                        <Image  width={32}
                                height={32}
                                auto={true}
                                src={record.userLogo || '//pic.qianmi.com/qmui/v0.2/img/avatar-default.png'}
                        />
                    </div>
                    <div className="order-info">
                        <p>
                            <span className="mr10">{`买家：${record.buyNickName}`}</span>
                            <span className="mr10 t-grayer">{`收货人：${record['consigneeInfo']['consigneeName']}`}</span>
                            <span className="mr10 t-grayer">{record['consigneeInfo', 'consigneeMobile']
                            || record['consigneeInfo', 'consigneePhone']}</span>
                        </p>
                        <p>
                            <span className="mr10">{`订单号：${record.tid}`}</span>
                            <span className="mr10 t-grayer">{record.payTypeName}</span>
                            <span className="mr10 t-grayer">{`配送方式：${record.shipMethodName}`}</span>
                            <span className="mr10 t-grayer">{`下单时间：${moment(record.ctime).format('YYYY/MM/DD HH:mm:ss')}`}</span>
                        </p>
                    </div>
                </Col>
            </Row>
        )
    }


    renderSubColumns() {
        const {receipt} = this.props;
        const {receipt_loading, tid} = this.state;


        return columns.concat([{
            title: '操作',
            width: 350,
            key: 'orderOpt',
            className: "ant-table-th-center pr8 va-t",
            render: (value, record, index)=>{
                return (
                    <div className="button-list t-right">
                        <Link to={`/order/receipt/${record.tid}`}><Button type="ghost" className="pushl">查看详情</Button></Link>
                        <ReceiptButton visible={tid === record.tid}
                                       loading={receipt_loading}
                                       onConfirm={()=>this.onConfirm(record.tid)}
                                       onCancel={this.onCancel}
                                       changeVisible={()=>this.changeVisible(record.tid)}/>
                    </div>
                )
            }
        }])
    }


    changeVisible = (pTid)=>{
        const {tid} = this.state;
        if (!tid) {
            this.setState({
                tid: pTid
            })
        } else {
            message.warn(`订单${tid}正在收款操作中，请先完成该订单收款`)
        }

    }


    /**
     * 收款
     * @param tid
     */
    onConfirm = (tid)=>{
        const {receipt, queryOrderList, resetPagination, completeOrder} = this.props;
        this.setState({
            receipt_loading: true
        });
        receipt(tid).then(()=>{
            setTimeout(()=>{
                message.success("收款成功");
                this.setState({
                    receipt_loading: false,
                    tid: ""
                });
                completeOrder(tid);
                resetPagination();
                queryOrderList();
            }, 2000);
        }).catch((err)=>{
            this.setState({
                receipt_loading: false
            });
            message.error(err.message);
        });
    }

    onCancel = ()=>{
        const {receipt_loading} = this.state;
        !receipt_loading && this.setState({tid: ""})
    }


    /**
     * 分页
     * @param pageNum
     * @param pageSize
     */
    changePageNum = (pageNum, pageSize)=>{
        const {changePageCode, queryOrderList} = this.props;
        changePageCode({pageNum});
        queryOrderList();
        this.scrollTop();
    }


    /**
     * 修改pageSize
     * @param current
     * @param pageSize
     */
    changePageSize = (current, pageSize)=>{
        const {changePageCode, queryOrderList} = this.props;
        changePageCode({
            pageNum: 1,
            pageSize
        });
        queryOrderList();
        this.scrollTop();
    }



    scrollTop(){
        if(this.pageWrapper){
            this.pageWrapper.scrollTop = 0;
        }else if(window.document.getElementById("react-content")){
            window.document.getElementById("react-content").getElementsByClassName("page-wrapper")[0].scrollTop = 0;
        }
    }
}